package com.cskaoyan.service;

import com.cskaoyan.bean.bo.WxAddressSaveBo;
import com.cskaoyan.bean.po.Address;
import com.cskaoyan.bean.po.AddressExample;
import com.cskaoyan.bean.po.Admin;
import com.cskaoyan.bean.po.User;
import com.cskaoyan.bean.vo.WxAddressListVO;
import com.cskaoyan.bean.vo.user.AddressDataListBean;
import com.cskaoyan.mapper.AddressMapper;
import com.cskaoyan.mapper.RegionMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author karlfu
 * @since 2022/06/07 20:48
 */

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    RegionMapper regionMapper;

    @Override
    public WxAddressListVO getAddressList(Integer userId) {

        WxAddressListVO wxAddressListVO = new WxAddressListVO();

        // 前端显示有问题 这里直接只查询最多七条数据
        wxAddressListVO.setPage(1);
        wxAddressListVO.setLimit(7);
        wxAddressListVO.setPages(1);

        AddressExample example = new AddressExample();
        AddressExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        example.setOrderByClause("update_time Desc");
        List<Address> addressList = addressMapper.selectByExample(example);
        List<Address> subList = null;
        if (addressList.size() > wxAddressListVO.getLimit()) {
            subList = addressList.subList(0, wxAddressListVO.getLimit());
        } else {
            subList = addressList;
        }

        wxAddressListVO.setList(subList);
        wxAddressListVO.setTotal(subList.size());

        return wxAddressListVO;
    }

    @Override
    public AddressDataListBean addressDetail(Integer id) {
        // 根据地址id查询数据库地址记录
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        if (id != null) {
            criteria.andIdEqualTo(id);
        }
        criteria.andDeletedEqualTo(false);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        // 转换成需要的返回对象
        if (addresses != null && addresses.size() == 1) {
            Address address = addresses.get(0);
            // 根据id查询省市区的名称
            String province = addressMapper.queryRegionNameById(Integer.parseInt(address.getProvince()));
            String city = addressMapper.queryRegionNameById(Integer.parseInt(address.getCity()));
            String country = addressMapper.queryRegionNameById(Integer.parseInt(address.getCounty()));
            return new AddressDataListBean(
                    address.getId(),
                    address.getName(),
                    address.getUserId(),
                    province, city, country,
                    address.getAddressDetail(),
                    address.getAreaCode(),
                    address.getTel(),
                    address.getIsDefault(),
                    address.getAddTime(),
                    address.getUpdateTime(),
                    address.getDeleted()
            );
        }
        return null;
    }

    @Override
    public Integer addressSave(WxAddressSaveBo wxAddressSaveBo) {
        // 判断是新建还是修改地址
        Integer id = wxAddressSaveBo.getId();
        if (id == 0){
            // 新建地址
            // 用户id
            Subject subject = SecurityUtils.getSubject();
            User primaryPrincipal = (User) subject.getPrincipals().getPrimaryPrincipal();
            Integer userId = primaryPrincipal.getId();
            // 查询省市区id
            // 省id 根据省名查询
            String provinceId = String.valueOf(regionMapper.queryRegionIdByName(wxAddressSaveBo.getProvince()));
            // 市id 根据市名和pid(其所属的省)查询
            String cityId = String.valueOf(regionMapper.queryRegionIdByNameAndPid(wxAddressSaveBo.getCity(),provinceId));
            // 区id 根据区名和pid(其所属的市)查询
            String countryId = String.valueOf(regionMapper.queryRegionIdByNameAndPid(wxAddressSaveBo.getCounty(),cityId));
            // 封装数据
            String postalCode = "";
            Date addTime = new Date();
            Date updateTime = new Date();
            Boolean deleted = false;
            Address newAddress = new Address(
                    null,
                    wxAddressSaveBo.getName(),
                    userId,provinceId,cityId,countryId,
                    wxAddressSaveBo.getAddressDetail(),
                    wxAddressSaveBo.getAreaCode(),
                    postalCode,
                    wxAddressSaveBo.getTel(),
                    wxAddressSaveBo.getIsDefault(),
                    addTime,updateTime,deleted
            );
            // 插入数据,先不管是不是默认地址，先插入数据
            int newAddressId = addressMapper.insertAddressRetureId(newAddress);
            if (wxAddressSaveBo.getIsDefault()){
                // 是默认地址，把数据库中已设为默认地址的变成不是默认地址
                addressMapper.updateToNotDefault(newAddressId);
            }
            return newAddressId;
        } else {
            // 修改地址
            // 通过地址id查询该条地址记录
            Address address = addressMapper.selectByPrimaryKey(wxAddressSaveBo.getId());
            address.setAreaCode(wxAddressSaveBo.getAreaCode());
            address.setIsDefault(wxAddressSaveBo.getIsDefault());
            address.setAddressDetail(wxAddressSaveBo.getAddressDetail());
            // 查询省市区id
            // 省id 根据省名查询
            String provinceId = String.valueOf(regionMapper.queryRegionIdByName(wxAddressSaveBo.getProvince()));
            // 市id 根据市名和pid(其所属的省)查询
            String cityId = String.valueOf(regionMapper.queryRegionIdByNameAndPid(wxAddressSaveBo.getCity(),provinceId));
            // 区id 根据区名和pid(其所属的市)查询
            String countryId = String.valueOf(regionMapper.queryRegionIdByNameAndPid(wxAddressSaveBo.getCounty(),cityId));
            address.setProvince(String.valueOf(provinceId));
            address.setCity(String.valueOf(cityId));
            address.setCounty(String.valueOf(countryId));
            address.setName(wxAddressSaveBo.getName());
            address.setTel(wxAddressSaveBo.getTel());
            // 修改该条记录
            // 将该条记录放回表达到更新
            addressMapper.updateByPrimaryKeySelective(address);
            if (wxAddressSaveBo.getIsDefault()){
                // 是默认地址，把数据库中已设为默认地址的变成不是默认地址
                addressMapper.updateToNotDefault(id);
            }
            return id;
        }

    }

    @Override
    public void addressDelete(Integer id) {
       addressMapper.deleteAddressByIdBySetDeleted(id);
    }
}
